import COS from 'cos-js-sdk-v5';
import type { COSConfig, UploadResult } from '@/types';

class COSService {
  private cos: COS | null = null;
  private config: COSConfig | null = null;

  // 初始化 COS 实例
  init(config: COSConfig) {
    this.config = config;
    this.cos = new COS({
      SecretId: config.SecretId,
      SecretKey: config.SecretKey,
    });
  }

  // 检查是否已初始化
  isInitialized(): boolean {
    return this.cos !== null && this.config !== null;
  }

  // 上传文件
  async uploadFile(file: File, key?: string): Promise<UploadResult> {
    if (!this.cos || !this.config) {
      throw new Error('COS 未初始化');
    }

    const fileKey = key || `daylog/${Date.now()}_${file.name}`;

    return new Promise((resolve, reject) => {
      this.cos!.uploadFile({
        Bucket: this.config!.Bucket,
        Region: this.config!.Region,
        Key: fileKey,
        Body: file,
        onProgress: (progressData) => {
          console.log('上传进度:', progressData.percent);
        }
      }, (err, data) => {
        if (err) {
          reject(err);
        } else if (data) {
          resolve({
            url: `https://${this.config!.Bucket}.cos.${this.config!.Region}.myqcloud.com/${fileKey}`,
            key: fileKey,
            etag: data.ETag
          });
        }
      });
    });
  }

  // 上传 JSON 数据
  async uploadJSON(data: any, key: string): Promise<UploadResult> {
    if (!this.cos || !this.config) {
      throw new Error('COS 未初始化');
    }

    const jsonString = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonString], { type: 'application/json' });

    return new Promise((resolve, reject) => {
      this.cos!.uploadFile({
        Bucket: this.config!.Bucket,
        Region: this.config!.Region,
        Key: key,
        Body: blob,
        onProgress: (progressData) => {
          console.log('上传进度:', progressData.percent);
        }
      }, (err, data) => {
        if (err) {
          reject(err);
        } else if (data) {
          resolve({
            url: `https://${this.config!.Bucket}.cos.${this.config!.Region}.myqcloud.com/${key}`,
            key: key,
            etag: data.ETag
          });
        }
      });
    });
  }

  // 下载 JSON 数据
  async downloadJSON(key: string): Promise<any> {
    if (!this.cos || !this.config) {
      throw new Error('COS 未初始化');
    }

    return new Promise((resolve, reject) => {
      this.cos!.getObject({
        Bucket: this.config!.Bucket,
        Region: this.config!.Region,
        Key: key,
      }, (err, data) => {
        if (err) {
          reject(err);
        } else if (data && data.Body) {
          const reader = new FileReader();
          reader.onload = () => {
            try {
              const jsonData = JSON.parse(reader.result as string);
              resolve(jsonData);
            } catch (parseErr) {
              reject(parseErr);
            }
          };
          reader.readAsText(data.Body as Blob);
        }
      });
    });
  }

  // 删除文件
  async deleteFile(key: string): Promise<void> {
    if (!this.cos || !this.config) {
      throw new Error('COS 未初始化');
    }

    return new Promise((resolve, reject) => {
      this.cos!.deleteObject({
        Bucket: this.config!.Bucket,
        Region: this.config!.Region,
        Key: key,
      }, (err) => {
        if (err) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }

  // 获取文件列表
  async listFiles(prefix?: string): Promise<string[]> {
    if (!this.cos || !this.config) {
      throw new Error('COS 未初始化');
    }

    return new Promise((resolve, reject) => {
      this.cos!.getBucket({
        Bucket: this.config!.Bucket,
        Region: this.config!.Region,
        Prefix: prefix || 'daylog/',
        MaxKeys: 1000,
      }, (err, data) => {
        if (err) {
          reject(err);
        } else if (data && data.Contents) {
          const keys = data.Contents.map(item => item.Key).filter(Boolean) as string[];
          resolve(keys);
        } else {
          resolve([]);
        }
      });
    });
  }

  // 备份本地数据到 COS
  async backupToCOS(notes: any[], categories: any[]): Promise<UploadResult> {
    const backupData = {
      notes,
      categories,
      backupTime: new Date().toISOString(),
      version: '1.0.0'
    };

    const key = `daylog/backup/backup_${Date.now()}.json`;
    return this.uploadJSON(backupData, key);
  }

  // 从 COS 恢复数据
  async restoreFromCOS(key: string): Promise<{ notes: any[], categories: any[] }> {
    const backupData = await this.downloadJSON(key);
    return {
      notes: backupData.notes || [],
      categories: backupData.categories || []
    };
  }
}

// 创建单例实例
export const cosService = new COSService(); 